package com.security.securityandoauth.handler;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/*
 * 自定义认证成功处理器 -- 认证成功后，返回给前端的数据
 */

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 获取用户身份信息
        Object principal = authentication.getPrincipal();
        // 获取用户凭证信息
        Object credentials = authentication.getCredentials();
        // 获取用户权限
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();

        // 封装数据
        Map<String, Object> data = new HashMap<>();
        data.put("code", 200);
        data.put("message", "认证成功");
        data.put("data", principal);
        String result = JSON.toJSONString(data);

        // 输出
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(result);

        // 认证成功，跳转至指定接口
        response.sendRedirect("/test");
    }
}
